Merge "objectcache: convert APC and hash BagOStuff to using mergeViaCas()"
[lhc/web/wiklou.git] / includes / specials / SpecialBlock.php
1 <?php
2 /**
3 * Implements Special:Block
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 use MediaWiki\Block\BlockRestriction;
25 use MediaWiki\Block\Restriction\PageRestriction;
26 use MediaWiki\Block\Restriction\NamespaceRestriction;
27
28 /**
29 * A special page that allows users with 'block' right to block users from
30 * editing pages and other actions
31 *
32 * @ingroup SpecialPage
33 */
34 class SpecialBlock extends FormSpecialPage {
35 /** @var User|string|null User to be blocked, as passed either by parameter (url?wpTarget=Foo)
36 * or as subpage (Special:Block/Foo) */
37 protected $target;
38
39 /** @var int Block::TYPE_ constant */
40 protected $type;
41
42 /** @var User|string The previous block target */
43 protected $previousTarget;
44
45 /** @var bool Whether the previous submission of the form asked for HideUser */
46 protected $requestedHideUser;
47
48 /** @var bool */
49 protected $alreadyBlocked;
50
51 /** @var array */
52 protected $preErrors = [];
53
54 public function __construct() {
55 parent::__construct( 'Block', 'block' );
56 }
57
58 public function doesWrites() {
59 return true;
60 }
61
62 /**
63 * Checks that the user can unblock themselves if they are trying to do so
64 *
65 * @param User $user
66 * @throws ErrorPageError
67 */
68 protected function checkExecutePermissions( User $user ) {
69 parent::checkExecutePermissions( $user );
70 # T17810: blocked admins should have limited access here
71 $status = self::checkUnblockSelf( $this->target, $user );
72 if ( $status !== true ) {
73 throw new ErrorPageError( 'badaccess', $status );
74 }
75 }
76
77 /**
78 * We allow certain special cases where user is blocked
79 *
80 * @return bool
81 */
82 public function requiresUnblock() {
83 return false;
84 }
85
86 /**
87 * Handle some magic here
88 *
89 * @param string $par
90 */
91 protected function setParameter( $par ) {
92 # Extract variables from the request. Try not to get into a situation where we
93 # need to extract *every* variable from the form just for processing here, but
94 # there are legitimate uses for some variables
95 $request = $this->getRequest();
96 list( $this->target, $this->type ) = self::getTargetAndType( $par, $request );
97 if ( $this->target instanceof User ) {
98 # Set the 'relevant user' in the skin, so it displays links like Contributions,
99 # User logs, UserRights, etc.
100 $this->getSkin()->setRelevantUser( $this->target );
101 }
102
103 list( $this->previousTarget, /*...*/ ) =
104 Block::parseTarget( $request->getVal( 'wpPreviousTarget' ) );
105 $this->requestedHideUser = $request->getBool( 'wpHideUser' );
106 }
107
108 /**
109 * Customizes the HTMLForm a bit
110 *
111 * @param HTMLForm $form
112 */
113 protected function alterForm( HTMLForm $form ) {
114 $form->setHeaderText( '' );
115 $form->setSubmitDestructive();
116
117 $msg = $this->alreadyBlocked ? 'ipb-change-block' : 'ipbsubmit';
118 $form->setSubmitTextMsg( $msg );
119
120 $this->addHelpLink( 'Help:Blocking users' );
121
122 # Don't need to do anything if the form has been posted
123 if ( !$this->getRequest()->wasPosted() && $this->preErrors ) {
124 $s = $form->formatErrors( $this->preErrors );
125 if ( $s ) {
126 $form->addHeaderText( Html::rawElement(
127 'div',
128 [ 'class' => 'error' ],
129 $s
130 ) );
131 }
132 }
133 }
134
135 protected function getDisplayFormat() {
136 return 'ooui';
137 }
138
139 /**
140 * Get the HTMLForm descriptor array for the block form
141 * @return array
142 */
143 protected function getFormFields() {
144 global $wgBlockAllowsUTEdit;
145
146 $this->getOutput()->enableOOUI();
147
148 $user = $this->getUser();
149
150 $suggestedDurations = self::getSuggestedDurations();
151
152 $conf = $this->getConfig();
153 $enablePartialBlocks = $conf->get( 'EnablePartialBlocks' );
154
155 $a = [];
156
157 $a['Target'] = [
158 'type' => 'user',
159 'ipallowed' => true,
160 'iprange' => true,
161 'id' => 'mw-bi-target',
162 'size' => '45',
163 'autofocus' => true,
164 'required' => true,
165 'validation-callback' => [ __CLASS__, 'validateTargetField' ],
166 'section' => 'target',
167 ];
168
169 $a['Editing'] = [
170 'type' => 'check',
171 'label-message' => 'block-prevent-edit',
172 'default' => true,
173 'section' => 'actions',
174 'disabled' => $enablePartialBlocks ? false : true,
175 ];
176
177 if ( $enablePartialBlocks ) {
178 $a['EditingRestriction'] = [
179 'type' => 'radio',
180 'cssclass' => 'mw-block-editing-restriction',
181 'options' => [
182 $this->msg( 'ipb-sitewide' )->escaped() .
183 new \OOUI\LabelWidget( [
184 'classes' => [ 'oo-ui-inline-help' ],
185 'label' => $this->msg( 'ipb-sitewide-help' )->text(),
186 ] ) => 'sitewide',
187 $this->msg( 'ipb-partial' )->escaped() .
188 new \OOUI\LabelWidget( [
189 'classes' => [ 'oo-ui-inline-help' ],
190 'label' => $this->msg( 'ipb-partial-help' )->text(),
191 ] ) => 'partial',
192 ],
193 'section' => 'actions',
194 ];
195 $a['PageRestrictions'] = [
196 'type' => 'titlesmultiselect',
197 'label' => $this->msg( 'ipb-pages-label' )->text(),
198 'exists' => true,
199 'max' => 10,
200 'cssclass' => 'mw-block-restriction',
201 'showMissing' => false,
202 'excludeDynamicNamespaces' => true,
203 'input' => [
204 'autocomplete' => false
205 ],
206 'section' => 'actions',
207 ];
208 $a['NamespaceRestrictions'] = [
209 'type' => 'namespacesmultiselect',
210 'label' => $this->msg( 'ipb-namespaces-label' )->text(),
211 'exists' => true,
212 'cssclass' => 'mw-block-restriction',
213 'input' => [
214 'autocomplete' => false
215 ],
216 'section' => 'actions',
217 ];
218 }
219
220 $a['CreateAccount'] = [
221 'type' => 'check',
222 'label-message' => 'ipbcreateaccount',
223 'default' => true,
224 'section' => 'actions',
225 ];
226
227 if ( self::canBlockEmail( $user ) ) {
228 $a['DisableEmail'] = [
229 'type' => 'check',
230 'label-message' => 'ipbemailban',
231 'section' => 'actions',
232 ];
233 }
234
235 if ( $wgBlockAllowsUTEdit ) {
236 $a['DisableUTEdit'] = [
237 'type' => 'check',
238 'label-message' => 'ipb-disableusertalk',
239 'default' => false,
240 'section' => 'actions',
241 ];
242 }
243
244 $a['Expiry'] = [
245 'type' => 'expiry',
246 'required' => true,
247 'options' => $suggestedDurations,
248 'default' => $this->msg( 'ipb-default-expiry' )->inContentLanguage()->text(),
249 'section' => 'expiry',
250 ];
251
252 $a['Reason'] = [
253 'type' => 'selectandother',
254 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
255 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
256 // Unicode codepoints.
257 'maxlength' => CommentStore::COMMENT_CHARACTER_LIMIT,
258 'maxlength-unit' => 'codepoints',
259 'options-message' => 'ipbreason-dropdown',
260 'section' => 'reason',
261 ];
262
263 $a['AutoBlock'] = [
264 'type' => 'check',
265 'label-message' => 'ipbenableautoblock',
266 'default' => true,
267 'section' => 'options',
268 ];
269
270 # Allow some users to hide name from block log, blocklist and listusers
271 if ( $user->isAllowed( 'hideuser' ) ) {
272 $a['HideUser'] = [
273 'type' => 'check',
274 'label-message' => 'ipbhidename',
275 'cssclass' => 'mw-block-hideuser',
276 'section' => 'options',
277 ];
278 }
279
280 # Watchlist their user page? (Only if user is logged in)
281 if ( $user->isLoggedIn() ) {
282 $a['Watch'] = [
283 'type' => 'check',
284 'label-message' => 'ipbwatchuser',
285 'section' => 'options',
286 ];
287 }
288
289 $a['HardBlock'] = [
290 'type' => 'check',
291 'label-message' => 'ipb-hardblock',
292 'default' => false,
293 'section' => 'options',
294 ];
295
296 # This is basically a copy of the Target field, but the user can't change it, so we
297 # can see if the warnings we maybe showed to the user before still apply
298 $a['PreviousTarget'] = [
299 'type' => 'hidden',
300 'default' => false,
301 ];
302
303 # We'll turn this into a checkbox if we need to
304 $a['Confirm'] = [
305 'type' => 'hidden',
306 'default' => '',
307 'label-message' => 'ipb-confirm',
308 'cssclass' => 'mw-block-confirm',
309 ];
310
311 // Block Id if a block already exists matching the target
312 $a['BlockId'] = [
313 'type' => 'hidden',
314 'default' => '',
315 ];
316
317 // Has the form been submitted
318 $a['WasPosted'] = [
319 'type' => 'hidden',
320 'default' => '',
321 ];
322
323 $this->maybeAlterFormDefaults( $a );
324
325 // Allow extensions to add more fields
326 Hooks::run( 'SpecialBlockModifyFormFields', [ $this, &$a ] );
327
328 return $a;
329 }
330
331 /**
332 * If the user has already been blocked with similar settings, load that block
333 * and change the defaults for the form fields to match the existing settings.
334 * @param array &$fields HTMLForm descriptor array
335 */
336 protected function maybeAlterFormDefaults( &$fields ) {
337 # This will be overwritten by request data
338 $fields['Target']['default'] = (string)$this->target;
339
340 if ( $this->target ) {
341 $status = self::validateTarget( $this->target, $this->getUser() );
342 if ( !$status->isOK() ) {
343 $errors = $status->getErrorsArray();
344 $this->preErrors = array_merge( $this->preErrors, $errors );
345 }
346 }
347
348 # This won't be
349 $fields['PreviousTarget']['default'] = (string)$this->target;
350
351 $block = Block::newFromTarget( $this->target );
352
353 if ( $block instanceof Block && !$block->mAuto # The block exists and isn't an autoblock
354 && ( $this->type != Block::TYPE_RANGE # The block isn't a rangeblock
355 || $block->getTarget() == $this->target ) # or if it is, the range is what we're about to block
356 ) {
357 $fields['HardBlock']['default'] = $block->isHardblock();
358 $fields['CreateAccount']['default'] = $block->isCreateAccountBlocked();
359 $fields['AutoBlock']['default'] = $block->isAutoblocking();
360
361 if ( isset( $fields['DisableEmail'] ) ) {
362 $fields['DisableEmail']['default'] = $block->isEmailBlocked();
363 }
364
365 if ( isset( $fields['HideUser'] ) ) {
366 $fields['HideUser']['default'] = $block->mHideName;
367 }
368
369 if ( isset( $fields['DisableUTEdit'] ) ) {
370 $fields['DisableUTEdit']['default'] = !$block->isUsertalkEditAllowed();
371 }
372
373 // If the username was hidden (ipb_deleted == 1), don't show the reason
374 // unless this user also has rights to hideuser: T37839
375 if ( !$block->mHideName || $this->getUser()->isAllowed( 'hideuser' ) ) {
376 $fields['Reason']['default'] = $block->mReason;
377 } else {
378 $fields['Reason']['default'] = '';
379 }
380
381 if ( $this->getRequest()->wasPosted() ) {
382 # Ok, so we got a POST submission asking us to reblock a user. So show the
383 # confirm checkbox; the user will only see it if they haven't previously
384 $fields['Confirm']['type'] = 'check';
385 } else {
386 # We got a target, but it wasn't a POST request, so the user must have gone
387 # to a link like [[Special:Block/User]]. We don't need to show the checkbox
388 # as long as they go ahead and block *that* user
389 $fields['Confirm']['default'] = 1;
390 }
391
392 if ( $block->mExpiry == 'infinity' ) {
393 $fields['Expiry']['default'] = 'infinite';
394 } else {
395 $fields['Expiry']['default'] = wfTimestamp( TS_RFC2822, $block->mExpiry );
396 }
397
398 $fields['BlockId']['default'] = $block->getId();
399
400 $this->alreadyBlocked = true;
401 $this->preErrors[] = [ 'ipb-needreblock', wfEscapeWikiText( (string)$block->getTarget() ) ];
402 }
403
404 if ( $this->getRequest()->wasPosted() ) {
405 $fields['WasPosted']['default'] = true;
406 }
407
408 # We always need confirmation to do HideUser
409 if ( $this->requestedHideUser ) {
410 $fields['Confirm']['type'] = 'check';
411 unset( $fields['Confirm']['default'] );
412 $this->preErrors[] = [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
413 }
414
415 # Or if the user is trying to block themselves
416 if ( (string)$this->target === $this->getUser()->getName() ) {
417 $fields['Confirm']['type'] = 'check';
418 unset( $fields['Confirm']['default'] );
419 $this->preErrors[] = [ 'ipb-blockingself', 'ipb-confirmaction' ];
420 }
421
422 if ( $this->getConfig()->get( 'EnablePartialBlocks' ) ) {
423 if ( $block instanceof Block && !$block->isSitewide() ) {
424 $fields['EditingRestriction']['default'] = 'partial';
425 } else {
426 $fields['EditingRestriction']['default'] = 'sitewide';
427 }
428
429 if ( $block instanceof Block ) {
430 $pageRestrictions = [];
431 $namespaceRestrictions = [];
432 foreach ( $block->getRestrictions() as $restriction ) {
433 switch ( $restriction->getType() ) {
434 case PageRestriction::TYPE:
435 if ( $restriction->getTitle() ) {
436 $pageRestrictions[] = $restriction->getTitle()->getPrefixedText();
437 }
438 break;
439 case NamespaceRestriction::TYPE:
440 $namespaceRestrictions[] = $restriction->getValue();
441 break;
442 }
443 }
444
445 if (
446 !$block->isSitewide() &&
447 empty( $pageRestrictions ) &&
448 empty( $namespaceRestrictions )
449 ) {
450 $fields['Editing']['default'] = false;
451 }
452
453 // Sort the restrictions so they are in alphabetical order.
454 sort( $pageRestrictions );
455 $fields['PageRestrictions']['default'] = implode( "\n", $pageRestrictions );
456 sort( $namespaceRestrictions );
457 $fields['NamespaceRestrictions']['default'] = implode( "\n", $namespaceRestrictions );
458 }
459 }
460 }
461
462 /**
463 * Add header elements like block log entries, etc.
464 * @return string
465 */
466 protected function preText() {
467 $this->getOutput()->addModuleStyles( [
468 'mediawiki.widgets.TagMultiselectWidget.styles',
469 'mediawiki.special',
470 ] );
471 $this->getOutput()->addModules( [ 'mediawiki.special.block' ] );
472
473 $blockCIDRLimit = $this->getConfig()->get( 'BlockCIDRLimit' );
474 $text = $this->msg( 'blockiptext', $blockCIDRLimit['IPv4'], $blockCIDRLimit['IPv6'] )->parse();
475
476 $otherBlockMessages = [];
477 if ( $this->target !== null ) {
478 $targetName = $this->target;
479 if ( $this->target instanceof User ) {
480 $targetName = $this->target->getName();
481 }
482 # Get other blocks, i.e. from GlobalBlocking or TorBlock extension
483 Hooks::run( 'OtherBlockLogLink', [ &$otherBlockMessages, $targetName ] );
484
485 if ( count( $otherBlockMessages ) ) {
486 $s = Html::rawElement(
487 'h2',
488 [],
489 $this->msg( 'ipb-otherblocks-header', count( $otherBlockMessages ) )->parse()
490 ) . "\n";
491
492 $list = '';
493
494 foreach ( $otherBlockMessages as $link ) {
495 $list .= Html::rawElement( 'li', [], $link ) . "\n";
496 }
497
498 $s .= Html::rawElement(
499 'ul',
500 [ 'class' => 'mw-blockip-alreadyblocked' ],
501 $list
502 ) . "\n";
503
504 $text .= $s;
505 }
506 }
507
508 return $text;
509 }
510
511 /**
512 * Add footer elements to the form
513 * @return string
514 */
515 protected function postText() {
516 $links = [];
517
518 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
519
520 $linkRenderer = $this->getLinkRenderer();
521 # Link to the user's contributions, if applicable
522 if ( $this->target instanceof User ) {
523 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $this->target->getName() );
524 $links[] = $linkRenderer->makeLink(
525 $contribsPage,
526 $this->msg( 'ipb-blocklist-contribs', $this->target->getName() )->text()
527 );
528 }
529
530 # Link to unblock the specified user, or to a blank unblock form
531 if ( $this->target instanceof User ) {
532 $message = $this->msg(
533 'ipb-unblock-addr',
534 wfEscapeWikiText( $this->target->getName() )
535 )->parse();
536 $list = SpecialPage::getTitleFor( 'Unblock', $this->target->getName() );
537 } else {
538 $message = $this->msg( 'ipb-unblock' )->parse();
539 $list = SpecialPage::getTitleFor( 'Unblock' );
540 }
541 $links[] = $linkRenderer->makeKnownLink(
542 $list,
543 new HtmlArmor( $message )
544 );
545
546 # Link to the block list
547 $links[] = $linkRenderer->makeKnownLink(
548 SpecialPage::getTitleFor( 'BlockList' ),
549 $this->msg( 'ipb-blocklist' )->text()
550 );
551
552 $user = $this->getUser();
553
554 # Link to edit the block dropdown reasons, if applicable
555 if ( $user->isAllowed( 'editinterface' ) ) {
556 $links[] = $linkRenderer->makeKnownLink(
557 $this->msg( 'ipbreason-dropdown' )->inContentLanguage()->getTitle(),
558 $this->msg( 'ipb-edit-dropdown' )->text(),
559 [],
560 [ 'action' => 'edit' ]
561 );
562 }
563
564 $text = Html::rawElement(
565 'p',
566 [ 'class' => 'mw-ipb-conveniencelinks' ],
567 $this->getLanguage()->pipeList( $links )
568 );
569
570 $userTitle = self::getTargetUserTitle( $this->target );
571 if ( $userTitle ) {
572 # Get relevant extracts from the block and suppression logs, if possible
573 $out = '';
574
575 LogEventsList::showLogExtract(
576 $out,
577 'block',
578 $userTitle,
579 '',
580 [
581 'lim' => 10,
582 'msgKey' => [ 'blocklog-showlog', $userTitle->getText() ],
583 'showIfEmpty' => false
584 ]
585 );
586 $text .= $out;
587
588 # Add suppression block entries if allowed
589 if ( $user->isAllowed( 'suppressionlog' ) ) {
590 LogEventsList::showLogExtract(
591 $out,
592 'suppress',
593 $userTitle,
594 '',
595 [
596 'lim' => 10,
597 'conds' => [ 'log_action' => [ 'block', 'reblock', 'unblock' ] ],
598 'msgKey' => [ 'blocklog-showsuppresslog', $userTitle->getText() ],
599 'showIfEmpty' => false
600 ]
601 );
602
603 $text .= $out;
604 }
605 }
606
607 return $text;
608 }
609
610 /**
611 * Get a user page target for things like logs.
612 * This handles account and IP range targets.
613 * @param User|string $target
614 * @return Title|null
615 */
616 protected static function getTargetUserTitle( $target ) {
617 if ( $target instanceof User ) {
618 return $target->getUserPage();
619 } elseif ( IP::isIPAddress( $target ) ) {
620 return Title::makeTitleSafe( NS_USER, $target );
621 }
622
623 return null;
624 }
625
626 /**
627 * Determine the target of the block, and the type of target
628 * @todo Should be in Block.php?
629 * @param string $par Subpage parameter passed to setup, or data value from
630 * the HTMLForm
631 * @param WebRequest|null $request Optionally try and get data from a request too
632 * @return array [ User|string|null, Block::TYPE_ constant|null ]
633 */
634 public static function getTargetAndType( $par, WebRequest $request = null ) {
635 $i = 0;
636 $target = null;
637
638 while ( true ) {
639 switch ( $i++ ) {
640 case 0:
641 # The HTMLForm will check wpTarget first and only if it doesn't get
642 # a value use the default, which will be generated from the options
643 # below; so this has to have a higher precedence here than $par, or
644 # we could end up with different values in $this->target and the HTMLForm!
645 if ( $request instanceof WebRequest ) {
646 $target = $request->getText( 'wpTarget', null );
647 }
648 break;
649 case 1:
650 $target = $par;
651 break;
652 case 2:
653 if ( $request instanceof WebRequest ) {
654 $target = $request->getText( 'ip', null );
655 }
656 break;
657 case 3:
658 # B/C @since 1.18
659 if ( $request instanceof WebRequest ) {
660 $target = $request->getText( 'wpBlockAddress', null );
661 }
662 break;
663 case 4:
664 break 2;
665 }
666
667 list( $target, $type ) = Block::parseTarget( $target );
668
669 if ( $type !== null ) {
670 return [ $target, $type ];
671 }
672 }
673
674 return [ null, null ];
675 }
676
677 /**
678 * HTMLForm field validation-callback for Target field.
679 * @since 1.18
680 * @param string $value
681 * @param array $alldata
682 * @param HTMLForm $form
683 * @return Message
684 */
685 public static function validateTargetField( $value, $alldata, $form ) {
686 $status = self::validateTarget( $value, $form->getUser() );
687 if ( !$status->isOK() ) {
688 $errors = $status->getErrorsArray();
689
690 return $form->msg( ...$errors[0] );
691 } else {
692 return true;
693 }
694 }
695
696 /**
697 * Validate a block target.
698 *
699 * @since 1.21
700 * @param string $value Block target to check
701 * @param User $user Performer of the block
702 * @return Status
703 */
704 public static function validateTarget( $value, User $user ) {
705 global $wgBlockCIDRLimit;
706
707 /** @var User $target */
708 list( $target, $type ) = self::getTargetAndType( $value );
709 $status = Status::newGood( $target );
710
711 if ( $type == Block::TYPE_USER ) {
712 if ( $target->isAnon() ) {
713 $status->fatal(
714 'nosuchusershort',
715 wfEscapeWikiText( $target->getName() )
716 );
717 }
718
719 $unblockStatus = self::checkUnblockSelf( $target, $user );
720 if ( $unblockStatus !== true ) {
721 $status->fatal( 'badaccess', $unblockStatus );
722 }
723 } elseif ( $type == Block::TYPE_RANGE ) {
724 list( $ip, $range ) = explode( '/', $target, 2 );
725
726 if (
727 ( IP::isIPv4( $ip ) && $wgBlockCIDRLimit['IPv4'] == 32 ) ||
728 ( IP::isIPv6( $ip ) && $wgBlockCIDRLimit['IPv6'] == 128 )
729 ) {
730 // Range block effectively disabled
731 $status->fatal( 'range_block_disabled' );
732 }
733
734 if (
735 ( IP::isIPv4( $ip ) && $range > 32 ) ||
736 ( IP::isIPv6( $ip ) && $range > 128 )
737 ) {
738 // Dodgy range
739 $status->fatal( 'ip_range_invalid' );
740 }
741
742 if ( IP::isIPv4( $ip ) && $range < $wgBlockCIDRLimit['IPv4'] ) {
743 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv4'] );
744 }
745
746 if ( IP::isIPv6( $ip ) && $range < $wgBlockCIDRLimit['IPv6'] ) {
747 $status->fatal( 'ip_range_toolarge', $wgBlockCIDRLimit['IPv6'] );
748 }
749 } elseif ( $type == Block::TYPE_IP ) {
750 # All is well
751 } else {
752 $status->fatal( 'badipaddress' );
753 }
754
755 return $status;
756 }
757
758 /**
759 * Given the form data, actually implement a block. This is also called from ApiBlock.
760 *
761 * @param array $data
762 * @param IContextSource $context
763 * @return bool|string
764 */
765 public static function processForm( array $data, IContextSource $context ) {
766 global $wgBlockAllowsUTEdit, $wgHideUserContribLimit;
767
768 $performer = $context->getUser();
769 $enablePartialBlocks = $context->getConfig()->get( 'EnablePartialBlocks' );
770 $isPartialBlock = $enablePartialBlocks &&
771 isset( $data['EditingRestriction'] ) &&
772 $data['EditingRestriction'] === 'partial';
773
774 // Handled by field validator callback
775 // self::validateTargetField( $data['Target'] );
776
777 # This might have been a hidden field or a checkbox, so interesting data
778 # can come from it
779 $data['Confirm'] = !in_array( $data['Confirm'], [ '', '0', null, false ], true );
780
781 /** @var User $target */
782 list( $target, $type ) = self::getTargetAndType( $data['Target'] );
783 if ( $type == Block::TYPE_USER ) {
784 $user = $target;
785 $target = $user->getName();
786 $userId = $user->getId();
787
788 # Give admins a heads-up before they go and block themselves. Much messier
789 # to do this for IPs, but it's pretty unlikely they'd ever get the 'block'
790 # permission anyway, although the code does allow for it.
791 # Note: Important to use $target instead of $data['Target']
792 # since both $data['PreviousTarget'] and $target are normalized
793 # but $data['target'] gets overridden by (non-normalized) request variable
794 # from previous request.
795 if ( $target === $performer->getName() &&
796 ( $data['PreviousTarget'] !== $target || !$data['Confirm'] )
797 ) {
798 return [ 'ipb-blockingself', 'ipb-confirmaction' ];
799 }
800 } elseif ( $type == Block::TYPE_RANGE ) {
801 $user = null;
802 $userId = 0;
803 } elseif ( $type == Block::TYPE_IP ) {
804 $user = null;
805 $target = $target->getName();
806 $userId = 0;
807 } else {
808 # This should have been caught in the form field validation
809 return [ 'badipaddress' ];
810 }
811
812 $expiryTime = self::parseExpiryInput( $data['Expiry'] );
813
814 if (
815 // an expiry time is needed
816 ( strlen( $data['Expiry'] ) == 0 ) ||
817 // can't be a larger string as 50 (it should be a time format in any way)
818 ( strlen( $data['Expiry'] ) > 50 ) ||
819 // check, if the time could be parsed
820 !$expiryTime
821 ) {
822 return [ 'ipb_expiry_invalid' ];
823 }
824
825 // an expiry time should be in the future, not in the
826 // past (wouldn't make any sense) - bug T123069
827 if ( $expiryTime < wfTimestampNow() ) {
828 return [ 'ipb_expiry_old' ];
829 }
830
831 if ( !isset( $data['DisableEmail'] ) ) {
832 $data['DisableEmail'] = false;
833 }
834
835 # If the user has done the form 'properly', they won't even have been given the
836 # option to suppress-block unless they have the 'hideuser' permission
837 if ( !isset( $data['HideUser'] ) ) {
838 $data['HideUser'] = false;
839 }
840
841 if ( $data['HideUser'] ) {
842 if ( !$performer->isAllowed( 'hideuser' ) ) {
843 # this codepath is unreachable except by a malicious user spoofing forms,
844 # or by race conditions (user has hideuser and block rights, loads block form,
845 # and loses hideuser rights before submission); so need to fail completely
846 # rather than just silently disable hiding
847 return [ 'badaccess-group0' ];
848 }
849
850 if ( $isPartialBlock ) {
851 return [ 'ipb_hide_partial' ];
852 }
853
854 # Recheck params here...
855 if ( $type != Block::TYPE_USER ) {
856 $data['HideUser'] = false; # IP users should not be hidden
857 } elseif ( !wfIsInfinity( $data['Expiry'] ) ) {
858 # Bad expiry.
859 return [ 'ipb_expiry_temp' ];
860 } elseif ( $wgHideUserContribLimit !== false
861 && $user->getEditCount() > $wgHideUserContribLimit
862 ) {
863 # Typically, the user should have a handful of edits.
864 # Disallow hiding users with many edits for performance.
865 return [ [ 'ipb_hide_invalid',
866 Message::numParam( $wgHideUserContribLimit ) ] ];
867 } elseif ( !$data['Confirm'] ) {
868 return [ 'ipb-confirmhideuser', 'ipb-confirmaction' ];
869 }
870 }
871
872 # Create block object.
873 $block = new Block();
874 $block->setTarget( $target );
875 $block->setBlocker( $performer );
876 $block->mReason = $data['Reason'][0];
877 $block->mExpiry = $expiryTime;
878 $block->isCreateAccountBlocked( $data['CreateAccount'] );
879 $block->isUsertalkEditAllowed( !$wgBlockAllowsUTEdit || !$data['DisableUTEdit'] );
880 $block->isEmailBlocked( $data['DisableEmail'] );
881 $block->isHardblock( $data['HardBlock'] );
882 $block->isAutoblocking( $data['AutoBlock'] );
883 $block->mHideName = $data['HideUser'];
884
885 if ( $isPartialBlock ) {
886 $block->isSitewide( false );
887 }
888
889 $reason = [ 'hookaborted' ];
890 if ( !Hooks::run( 'BlockIp', [ &$block, &$performer, &$reason ] ) ) {
891 return $reason;
892 }
893
894 $pageRestrictions = [];
895 $namespaceRestrictions = [];
896 if ( $enablePartialBlocks ) {
897 if ( $data['PageRestrictions'] !== '' ) {
898 $pageRestrictions = array_map( function ( $text ) {
899 $title = Title::newFromText( $text );
900 // Use the link cache since the title has already been loaded when
901 // the field was validated.
902 $restriction = new PageRestriction( 0, $title->getArticleID() );
903 $restriction->setTitle( $title );
904 return $restriction;
905 }, explode( "\n", $data['PageRestrictions'] ) );
906 }
907 if ( $data['NamespaceRestrictions'] !== '' ) {
908 $namespaceRestrictions = array_map( function ( $id ) {
909 return new NamespaceRestriction( 0, $id );
910 }, explode( "\n", $data['NamespaceRestrictions'] ) );
911 }
912
913 $restrictions = ( array_merge( $pageRestrictions, $namespaceRestrictions ) );
914 $block->setRestrictions( $restrictions );
915 }
916
917 $priorBlock = null;
918 # Try to insert block. Is there a conflicting block?
919 $status = $block->insert();
920 if ( !$status ) {
921 # Indicates whether the user is confirming the block and is aware of
922 # the conflict (did not change the block target in the meantime)
923 $blockNotConfirmed = !$data['Confirm'] || ( array_key_exists( 'PreviousTarget', $data )
924 && $data['PreviousTarget'] !== $target );
925
926 # Special case for API - T34434
927 $reblockNotAllowed = ( array_key_exists( 'Reblock', $data ) && !$data['Reblock'] );
928
929 # Show form unless the user is already aware of this...
930 if ( $blockNotConfirmed || $reblockNotAllowed ) {
931 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
932 # Otherwise, try to update the block...
933 } else {
934 # This returns direct blocks before autoblocks/rangeblocks, since we should
935 # be sure the user is blocked by now it should work for our purposes
936 $currentBlock = Block::newFromTarget( $target );
937 if ( $block->equals( $currentBlock ) ) {
938 return [ [ 'ipb_already_blocked', $block->getTarget() ] ];
939 }
940 # If the name was hidden and the blocking user cannot hide
941 # names, then don't allow any block changes...
942 if ( $currentBlock->mHideName && !$performer->isAllowed( 'hideuser' ) ) {
943 return [ 'cant-see-hidden-user' ];
944 }
945
946 $priorBlock = clone $currentBlock;
947 $currentBlock->isHardblock( $block->isHardblock() );
948 $currentBlock->isCreateAccountBlocked( $block->isCreateAccountBlocked() );
949 $currentBlock->mExpiry = $block->mExpiry;
950 $currentBlock->isAutoblocking( $block->isAutoblocking() );
951 $currentBlock->mHideName = $block->mHideName;
952 $currentBlock->isEmailBlocked( $block->isEmailBlocked() );
953 $currentBlock->isUsertalkEditAllowed( $block->isUsertalkEditAllowed() );
954 $currentBlock->mReason = $block->mReason;
955
956 if ( $enablePartialBlocks ) {
957 // Maintain the sitewide status. If partial blocks is not enabled,
958 // saving the block will result in a sitewide block.
959 $currentBlock->isSitewide( $block->isSitewide() );
960
961 // Set the block id of the restrictions.
962 $currentBlock->setRestrictions(
963 BlockRestriction::setBlockId( $currentBlock->getId(), $restrictions )
964 );
965 }
966
967 $status = $currentBlock->update();
968 // TODO handle failure
969
970 $logaction = 'reblock';
971
972 # Unset _deleted fields if requested
973 if ( $currentBlock->mHideName && !$data['HideUser'] ) {
974 RevisionDeleteUser::unsuppressUserName( $target, $userId );
975 }
976
977 # If hiding/unhiding a name, this should go in the private logs
978 if ( (bool)$currentBlock->mHideName ) {
979 $data['HideUser'] = true;
980 }
981
982 $block = $currentBlock;
983 }
984 } else {
985 $logaction = 'block';
986 }
987
988 Hooks::run( 'BlockIpComplete', [ $block, $performer, $priorBlock ] );
989
990 # Set *_deleted fields if requested
991 if ( $data['HideUser'] ) {
992 RevisionDeleteUser::suppressUserName( $target, $userId );
993 }
994
995 # Can't watch a rangeblock
996 if ( $type != Block::TYPE_RANGE && $data['Watch'] ) {
997 WatchAction::doWatch(
998 Title::makeTitle( NS_USER, $target ),
999 $performer,
1000 User::IGNORE_USER_RIGHTS
1001 );
1002 }
1003
1004 # Block constructor sanitizes certain block options on insert
1005 $data['BlockEmail'] = $block->isEmailBlocked();
1006 $data['AutoBlock'] = $block->isAutoblocking();
1007
1008 # Prepare log parameters
1009 $logParams = [];
1010 $logParams['5::duration'] = $data['Expiry'];
1011 $logParams['6::flags'] = self::blockLogFlags( $data, $type );
1012 $logParams['sitewide'] = $block->isSitewide();
1013
1014 if ( $enablePartialBlocks && !$block->isSitewide() ) {
1015 if ( $data['PageRestrictions'] !== '' ) {
1016 $logParams['7::restrictions']['pages'] = explode( "\n", $data['PageRestrictions'] );
1017 }
1018
1019 if ( $data['NamespaceRestrictions'] !== '' ) {
1020 $logParams['7::restrictions']['namespaces'] = explode( "\n", $data['NamespaceRestrictions'] );
1021 }
1022 }
1023
1024 # Make log entry, if the name is hidden, put it in the suppression log
1025 $log_type = $data['HideUser'] ? 'suppress' : 'block';
1026 $logEntry = new ManualLogEntry( $log_type, $logaction );
1027 $logEntry->setTarget( Title::makeTitle( NS_USER, $target ) );
1028 $logEntry->setComment( $data['Reason'][0] );
1029 $logEntry->setPerformer( $performer );
1030 $logEntry->setParameters( $logParams );
1031 # Relate log ID to block ID (T27763)
1032 $logEntry->setRelations( [ 'ipb_id' => $block->getId() ] );
1033 $logId = $logEntry->insert();
1034
1035 if ( !empty( $data['Tags'] ) ) {
1036 $logEntry->setTags( $data['Tags'] );
1037 }
1038
1039 $logEntry->publish( $logId );
1040
1041 return true;
1042 }
1043
1044 /**
1045 * Get an array of suggested block durations from MediaWiki:Ipboptions
1046 * @todo FIXME: This uses a rather odd syntax for the options, should it be converted
1047 * to the standard "**<duration>|<displayname>" format?
1048 * @param Language|null $lang The language to get the durations in, or null to use
1049 * the wiki's content language
1050 * @param bool $includeOther Whether to include the 'other' option in the list of
1051 * suggestions
1052 * @return array
1053 */
1054 public static function getSuggestedDurations( Language $lang = null, $includeOther = true ) {
1055 $a = [];
1056 $msg = $lang === null
1057 ? wfMessage( 'ipboptions' )->inContentLanguage()->text()
1058 : wfMessage( 'ipboptions' )->inLanguage( $lang )->text();
1059
1060 if ( $msg == '-' ) {
1061 return [];
1062 }
1063
1064 foreach ( explode( ',', $msg ) as $option ) {
1065 if ( strpos( $option, ':' ) === false ) {
1066 $option = "$option:$option";
1067 }
1068
1069 list( $show, $value ) = explode( ':', $option );
1070 $a[$show] = $value;
1071 }
1072
1073 if ( $a && $includeOther ) {
1074 // if options exist, add other to the end instead of the begining (which
1075 // is what happens by default).
1076 $a[ wfMessage( 'ipbother' )->text() ] = 'other';
1077 }
1078
1079 return $a;
1080 }
1081
1082 /**
1083 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1084 * ("24 May 2034", etc), into an absolute timestamp we can put into the database.
1085 *
1086 * @todo strtotime() only accepts English strings. This means the expiry input
1087 * can only be specified in English.
1088 * @see https://secure.php.net/manual/en/function.strtotime.php
1089 *
1090 * @param string $expiry Whatever was typed into the form
1091 * @return string|bool Timestamp or 'infinity' or false on error.
1092 */
1093 public static function parseExpiryInput( $expiry ) {
1094 if ( wfIsInfinity( $expiry ) ) {
1095 return 'infinity';
1096 }
1097
1098 $expiry = strtotime( $expiry );
1099
1100 if ( $expiry < 0 || $expiry === false ) {
1101 return false;
1102 }
1103
1104 return wfTimestamp( TS_MW, $expiry );
1105 }
1106
1107 /**
1108 * Can we do an email block?
1109 * @param User $user The sysop wanting to make a block
1110 * @return bool
1111 */
1112 public static function canBlockEmail( $user ) {
1113 global $wgEnableUserEmail, $wgSysopEmailBans;
1114
1115 return ( $wgEnableUserEmail && $wgSysopEmailBans && $user->isAllowed( 'blockemail' ) );
1116 }
1117
1118 /**
1119 * T17810: blocked admins should not be able to block/unblock
1120 * others, and probably shouldn't be able to unblock themselves
1121 * either.
1122 *
1123 * Exception: Users can block the user who blocked them, to reduce
1124 * advantage of a malicious account blocking all admins (T150826)
1125 *
1126 * @param User|int|string|null $target Target to block or unblock; could be a User object,
1127 * or a user ID or username, or null when the target is not known yet (e.g. when
1128 * displaying Special:Block)
1129 * @param User $performer User doing the request
1130 * @return bool|string True or error message key
1131 */
1132 public static function checkUnblockSelf( $target, User $performer ) {
1133 if ( is_int( $target ) ) {
1134 $target = User::newFromId( $target );
1135 } elseif ( is_string( $target ) ) {
1136 $target = User::newFromName( $target );
1137 }
1138 if ( $performer->isBlocked() ) {
1139 if ( $target instanceof User && $target->getId() == $performer->getId() ) {
1140 # User is trying to unblock themselves
1141 if ( $performer->isAllowed( 'unblockself' ) ) {
1142 return true;
1143 # User blocked themselves and is now trying to reverse it
1144 } elseif ( $performer->blockedBy() === $performer->getName() ) {
1145 return true;
1146 } else {
1147 return 'ipbnounblockself';
1148 }
1149 } elseif (
1150 $target instanceof User &&
1151 $performer->getBlock() instanceof Block &&
1152 $performer->getBlock()->getBy() &&
1153 $performer->getBlock()->getBy() === $target->getId()
1154 ) {
1155 // Allow users to block the user that blocked them.
1156 // This is to prevent a situation where a malicious user
1157 // blocks all other users. This way, the non-malicious
1158 // user can block the malicious user back, resulting
1159 // in a stalemate.
1160 return true;
1161
1162 } else {
1163 # User is trying to block/unblock someone else
1164 return 'ipbblocked';
1165 }
1166 } else {
1167 return true;
1168 }
1169 }
1170
1171 /**
1172 * Return a comma-delimited list of "flags" to be passed to the log
1173 * reader for this block, to provide more information in the logs
1174 * @param array $data From HTMLForm data
1175 * @param int $type Block::TYPE_ constant (USER, RANGE, or IP)
1176 * @return string
1177 */
1178 protected static function blockLogFlags( array $data, $type ) {
1179 $config = RequestContext::getMain()->getConfig();
1180
1181 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1182
1183 $flags = [];
1184
1185 # when blocking a user the option 'anononly' is not available/has no effect
1186 # -> do not write this into log
1187 if ( !$data['HardBlock'] && $type != Block::TYPE_USER ) {
1188 // For grepping: message block-log-flags-anononly
1189 $flags[] = 'anononly';
1190 }
1191
1192 if ( $data['CreateAccount'] ) {
1193 // For grepping: message block-log-flags-nocreate
1194 $flags[] = 'nocreate';
1195 }
1196
1197 # Same as anononly, this is not displayed when blocking an IP address
1198 if ( !$data['AutoBlock'] && $type == Block::TYPE_USER ) {
1199 // For grepping: message block-log-flags-noautoblock
1200 $flags[] = 'noautoblock';
1201 }
1202
1203 if ( $data['DisableEmail'] ) {
1204 // For grepping: message block-log-flags-noemail
1205 $flags[] = 'noemail';
1206 }
1207
1208 if ( $blockAllowsUTEdit && $data['DisableUTEdit'] ) {
1209 // For grepping: message block-log-flags-nousertalk
1210 $flags[] = 'nousertalk';
1211 }
1212
1213 if ( $data['HideUser'] ) {
1214 // For grepping: message block-log-flags-hiddenname
1215 $flags[] = 'hiddenname';
1216 }
1217
1218 return implode( ',', $flags );
1219 }
1220
1221 /**
1222 * Process the form on POST submission.
1223 * @param array $data
1224 * @param HTMLForm|null $form
1225 * @return bool|array True for success, false for didn't-try, array of errors on failure
1226 */
1227 public function onSubmit( array $data, HTMLForm $form = null ) {
1228 // If "Editing" checkbox is unchecked, the block must be a partial block affecting
1229 // actions other than editing, and there must be no restrictions.
1230 if ( isset( $data['Editing'] ) && $data['Editing'] === false ) {
1231 $data['EditingRestriction'] = 'partial';
1232 $data['PageRestrictions'] = '';
1233 $data['NamespaceRestrictions'] = '';
1234 }
1235 return self::processForm( $data, $form->getContext() );
1236 }
1237
1238 /**
1239 * Do something exciting on successful processing of the form, most likely to show a
1240 * confirmation message
1241 */
1242 public function onSuccess() {
1243 $out = $this->getOutput();
1244 $out->setPageTitle( $this->msg( 'blockipsuccesssub' ) );
1245 $out->addWikiMsg( 'blockipsuccesstext', wfEscapeWikiText( $this->target ) );
1246 }
1247
1248 /**
1249 * Return an array of subpages beginning with $search that this special page will accept.
1250 *
1251 * @param string $search Prefix to search for
1252 * @param int $limit Maximum number of results to return (usually 10)
1253 * @param int $offset Number of results to skip (usually 0)
1254 * @return string[] Matching subpages
1255 */
1256 public function prefixSearchSubpages( $search, $limit, $offset ) {
1257 $user = User::newFromName( $search );
1258 if ( !$user ) {
1259 // No prefix suggestion for invalid user
1260 return [];
1261 }
1262 // Autocomplete subpage as user list - public to allow caching
1263 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
1264 }
1265
1266 protected function getGroupName() {
1267 return 'users';
1268 }
1269 }